<?php
namespace plugins\goods\controller;

use cmf\controller\PluginAdminBaseController; //引入此类
use plugins\goods\interfaceLib\GoodsSpecClassify;
use plugins\goods\model\GoodsModel;
use plugins\goods\model\GoodsSpecModel;
use plugins\store\Common;
use think\Db;
use tree\Tree;

class GoodsSpecController extends PluginAdminBaseController
{
    //首页
    public function index()
    {
        $param  = $this->request->param();
        $where  = 1;
        $search = '';
        if (!empty($param['search'])) {
            $where .= " and module_name like '%" . $param['search'] . "%'";
            $search = $param['search'];
        }
        $this->assign('search', $search);
        //店铺id过滤
        $is_admin = Common::getAllowAccess();
        if (true !== $is_admin) {
            $where .= " and store_id = '{$is_admin}'";
        }
        $list = db('goods_spec')->where($where)->select()->toArray();
        $spec = new GoodsSpecModel();
        $spec->setlist($list);
        $list = $spec->list;
        foreach ($list as $key => &$value) {
            $info         = db('goods_cats')->field('catname')->where(['catid' => $value['cid']])->find();
            $value['cid'] = $info['catname'];
        }
        $this->assign('list', $list);
        return $this->fetch();
    }
    //详情页
    public function detail()
    {
        $param = $this->request->param();
        $spec  = new GoodsSpecModel();
        $spec->setinfo($param['spec_id']);
        $info        = $spec->info;
        $search      = db('goods_cats')->field('catname')->where(['catid' => $info['cid']])->find();
        $info['cid'] = $search['catname'];
        $this->assign('info', $info);
        return $this->fetch();
    }
    //添加界面
    public function addspecpage()
    {
        $list = db('goods_cats')->field('catid as id,pid as parent_id,catname')->order('catsort')->where(['isshow' => 1])->select()->toArray();
        /*tree设置*/
        $tree       = new Tree();
        $tree->icon = ['&nbsp;&nbsp;&nbsp;&nbsp│', '&nbsp;&nbsp;&nbsp;&nbsp;├', '&nbsp;&nbsp;&nbsp;&nbsp;└'];
        $str        = "<option value=\$id \$selected>\$spacer \$catname</option>";
        //内容放入
        $tree->init($list);
        //tree生成
        $select = $tree->getTree('0', $str);
        $this->assign('select', $select);
        return $this->fetch();
    }
    //添加
    public function addspec()
    {
        $param = $this->request->param();
        //店铺id过滤
        $is_admin = Common::getAllowAccess();
        if (true !== $is_admin) {
            $param['store_id'] = $is_admin;
        } else {
            $param['store_id'] = 'admin';
        }
        if (empty($param['spec'])) {
            $this->error('规格不能为空');
        }
        if (empty($param['attr'])) {
            return $this->error('属性不能为空');
        }
        //检测重名
        // $check = db('goods_spec')->where(['module_name' => $param['module_name']])->find();
        // if ($check) {
        //     return $this->error('已被占用的模板名称');
        // }
        $da = [
            'module_name' => $param['module_name'],
            'cid'         => $param['cid'],
            'store_id'    => $param['store_id'],
        ];
        //spec表插入
        $result = db('goods_spec')->insertGetId($da);
        if ($result) {
            if (!empty($param['spec']['add'])) {
                //spec_name表插入
                foreach ($param['spec']['add'] as $key => $value) {
                    $name_id = db('goods_spec_name')->insertGetId(['spec_id' => $result, 'spec_name' => $value]);
                    if (empty($param['attr'][$key])) {
                        continue;
                    }
                    //spec_attr表插入
                    foreach ($param['attr'][$key] as $k => $v) {
                        db('goods_spec_attr')->insert(['attr_name' => $v, 'name_id' => $name_id]);
                    }
                }
            }
            return $this->success('添加成功');
        } else {
            return $this->error('添加失败');
        }
    }
    //删除规格
    public function delete()
    {
        $param = $this->request->param();
        if (empty($param['spec_id'])) {
            return $this->error('请先选择要删除的规格！');
        }

        $goods_spec = new GoodsSpecModel;
        $affirm_del = $goods_spec->affirmDelete( $param['spec_id'] );

        if ($affirm_del['goods_count'] != 0) {
            return $this->error('规格有'.$affirm_del['goods_count'].'个商品正在被使用中，无法删除，请检查规格下是否有上架商品或审核中商品');
        }

        if (is_array($param['spec_id'])) {
            $result = Db::name('goods_spec')->where('spec_id', 'in', $param['spec_id'])->delete();
        } else {
            $result = Db::name('goods_spec')->where('spec_id', $param['spec_id'])->delete();
        }
        if ($result) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }


    //编辑界面
    public function editPage()
    {
        $param = $this->request->param();
        $spec  = new GoodsSpecModel();
        $spec->setinfo($param['spec_id']);
        $this->assign('info', $spec->info);
        $arr  = $spec->info;
        $list = db('goods_cats')->field('catid as id,pid as parent_id,catname')->order('catsort')->where(['isshow' => 1])->select()->toArray();
        /*tree设置*/
        $tree       = new Tree();
        $tree->icon = ['&nbsp;&nbsp;&nbsp;&nbsp│', '&nbsp;&nbsp;&nbsp;&nbsp;├', '&nbsp;&nbsp;&nbsp;&nbsp;└'];
        foreach ($list as $key => &$value) {
            if ($value['id'] == $arr['cid']) {
                $value['selected'] = "selected='selected'";
            }
        }
        $str = "<option value=\$id \$selected>\$spacer \$catname</option>";
        //内容放入
        $tree->init($list);
        //tree生成
        $select = $tree->getTree('0', $str);
        $this->assign('select', $select);
        return $this->fetch();
    }
    //更新规格
    public function editSpec()
    {
        $param = $this->request->param();
        //module_name的更新
        db('goods_spec')->where(['spec_id' => $param['spec_id']])->update(['module_name' => $param['module_name'], 'cid' => $param['cid']]);
        if (!empty($param['spec']['update'])) {
            //spec_name的更新
            foreach ($param['spec']['update'] as $key => $value) {
                //更新规格名
                db('goods_spec_name')->where(['name_id' => $key])->update(['spec_name' => $value]);
                //更新规格属性
                if (!empty($param['attr']['update'][$key])) {
                    foreach ($param['attr']['update'][$key] as $k => $v) {
                        db('goods_spec_attr')->where(['attr_id' => $k])->update(['attr_name' => $v]);
                    }
                }
            }
        }
        if (!empty($param['spec']['add'])) {
            //spec_name的添加
            foreach ($param['spec']['add'] as $key => $value) {
                $name_id = db('goods_spec_name')->insertGetId(['spec_name' => $value, 'spec_id' => $param['spec_id']]);
                if (!empty($param['attr']['add'][$key])) {
                    foreach ($param['attr']['add'][$key] as $k => $v) {
                        db('goods_spec_attr')->insert(['name_id' => $name_id, 'attr_name' => $v]);
                    }
                }
            }
        }
        return $this->success('编辑成功');
    }
    //原有规格删除
    public function deletename()
    {
        $param = $this->request->param();
        db('goods_spec_name')->where(['name_id' => $param['id']])->delete();
        db('goods_spec_attr')->where(['name_id' => $param['id']])->delete();
    }
    //原有规格名中添加属性
    public function addattr()
    {
        $param   = $this->request->param();
        $attr_id = db('goods_spec_attr')->insertGetId(['name_id' => $param['id']]);
        return $attr_id;
    }
    //原有规格删除属性
    public function deleteattr()
    {
        $param = $this->request->param();
        db('goods_spec_attr')->where(['attr_id' => $param['id']])->delete();
    }
    // public function test(){
    //     $tableName = 'goods';
    //     //验证表是否存在
    //     //这是要查询的表的原始名称（全名）
    //     $tableName = config('database.prefix').$tableName;
    //     $isTable = db()->query('SHOW TABLES LIKE '."'".$tableName."'");
    //     if($isTable){
    //         echo '有';
    //     }else{
    //         echo '无';
    //     }
    // }
    //选择分类后生成规格选项
    public function specchoose()
    {
        $param = $this->request->param();
        $model = new GoodsSpecClassify();
        $html  = $model->pidGetSpec($param['name'], $id = null, $param['cid']);
        return $html;
    }

    

    //选择规格选项后生成表格
    public function spectable()
    {
        $param = $this->request->post();
        $model = new GoodsSpecClassify();

        $param['data'] = !empty($param['data']) ? $param['data'] : [];
        $html  = $model->cartesiantable($param['data'], $param['name']);
        return $html;
    }
    // //规格图片上传
    // public function pzUpload()
    // {
    //     $param = $this->request->param();
    //     //文件夹的标识
    //     $info = $param['info'];
    //     $file = $_FILES['file']; //获取上传的文件
    //     //存储时的文件名
    //     //后缀
    //     $kz = substr($file['name'], strrpos($file['name'], '.'));
    //     //随机数
    //     $sui      = mt_rand(10000000, 99999999);
    //     $filename = $info . "/" . date('Ymd') . "/" . $sui . $file['name'];
    //     $pic      = 'plugins/goods/view/image/' . $filename;
    //     if (!is_dir('plugins/goods/view/image/' . $info . "/" . date('Ymd'))) {
    //         //判断目录是否存在 不存在就创建 并赋予777权限
    //         mkdir('plugins/goods/view/image/' . $info . "/" . date('Ymd'), 0777, true);
    //     }
    //     // 进行文件移动
    //     if (move_uploaded_file($file['tmp_name'], iconv("UTF-8", "gb2312", $pic))) {
    //         return json(['save' => $filename, 'info' => $info]); //传回文件地址
    //     }
    // }

    public function pzUpload(){
        $param = $this->request->param();

        //模块的标识
        $module = $param['_plugin'];
        //文件夹的标识
        $info = $param['info'];
        //获取上传的文件
        $file = $_FILES['file'];    

        $res = fileUpload($file,$module,$info);

        if($res['status'] == true){
            return json(['save'=>$res['data'],'info'=>$info]);
        }

    }    

    /**
     * 商品规格详情
     */
    public function goodsSpecDetail()
    {
        $data = $this->request->param();
        $gid  = $data['id'];

        $goods = GoodsModel::where('id', $gid)->find();
        //获取分类id
        $where    = 1;
        $is_admin = Common::getAllowAccess();
        if (true === $is_admin) {
            $is_admin = 'admin';
        }
        $where .= " and store_id = '{$is_admin}'";
        $spec = db('goods_spec')->where($where)->where(['cid' => $goods['catid']])->find();

        $model = new GoodsSpecModel();
        $model->setinfo($spec['spec_id']);
        $info = $model->info;

        //gid获得已有配置
        $configs  = db('goods_spec_list')->where(['gid' => $gid])->select()->toArray();
        $selected = [];
        foreach ($configs as $key => &$value) {

            $value['img'] = $value['img'] ? '/plugins/goods/view/image/' . $value['img'] : '';
            //已选中的部分
            $arr              = explode("#*_*#", $value['attr']);
            $value['attr_id'] = $arr;

            $attr_names = '';
            foreach ($arr as $k => &$v) {
                $selected[] = $v;
                $attr_name  = db('goods_spec_attr')->where(['attr_id' => $v])->find();
                $v          = $attr_name['attr_name'];

                $attr_names .= $v . ',';
            }
            $value['attr_name'] = $attr_names;
        }
        $this->assign('info', $info);
        $this->assign('selected', $selected);
        $this->assign('configs', $configs);

        return $this->fetch('goods_spec/goodsSpecDetail');
    }

    /**
     * 保存商品规格
     */
    public function saveGoodsSpec()
    {
        $data = $this->request->param();
        $inventory = 0;
        foreach ($data['id'] as $key => $value) {
            $upd = [
                'price' => $data['price'][$key],
                'num'   => $data['num'][$key],
                'limit' => $data['limit'][$key],
            ];
            $spec = db('goods_spec_list')->where('id', $value)->update($upd);
        }

        return $this->success('操作成功');
    }

    /**
     * 根据模板id获取规格信息
     */
    public function getSpecAttrHtml()
    {
        $param = $this->request->param();

        $name = $param['name'];
        $spec_id = $param['spec_id'];
        $model = new GoodsSpecClassify();
        $html  = $model->getSpecAttrHtml($name, null, $spec_id);

        return $html;
    }


}
